package com.meiyu.live.ui.main;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Response;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.umeng.socialize.UMShareAPI;
import com.meiyu.live.BaseActivity;
import com.meiyu.live.R;
import com.meiyu.live.comm.Constant;
import com.meiyu.live.comm.UserConfig;
import com.meiyu.live.eventbus.FocusEvent;
import com.meiyu.live.net.param.AnchorParams;
import com.meiyu.live.net.param.BoughtParams;
import com.meiyu.live.net.param.IsfocusParams;
import com.meiyu.live.net.response.AnchorInfoResponse;
import com.meiyu.live.net.response.BaseResponse;
import com.meiyu.live.popj.Anchor;
import com.meiyu.live.popj.Hookup;
import com.meiyu.live.ui.login.LoginActivity;
import com.meiyu.live.util.ToastUtil;
import com.meiyu.live.widget.AppointDialog;
import com.meiyu.live.widget.Banner;
import com.meiyu.live.widget.BannerConfig;
import com.meiyu.live.widget.NetLoadingDailog;
import com.meiyu.live.widget.ShareDialog;

import java.text.SimpleDateFormat;
import java.util.ArrayList;

import de.greenrobot.event.EventBus;

/**
 * 主播资料
 * Created by zbl on 2016/9/22.
 */
public class AnchorDetailActivity extends BaseActivity implements View.OnClickListener {

    public static final String VERIFY_ID = "verify_id";
    public static final int REUQEST_LOGIN = 1;

    private NetLoadingDailog dialog_loading;
    private AppointDialog appointDialog;
    private ShareDialog shareDialog;
    private ImageLoader imageLoader;
    private DisplayImageOptions options;

    private View btn_back;
    private ImageView iv_main, iv_video_flag, iv_like;
    private Banner mBanner;
    private TextView tv_anchor_introduction, btn_appoint;
    private TextView tv_time, tv_progress, tv_appoint_count, tv_time_left;
    private View btn_follow, btn_share, layout_bottom_btn;
    private TextView tv_follow;

    private long verify_id;
    private Anchor anchorBean;

    public static void start(Context context, Hookup bean) {
        Intent intent = new Intent(context, AnchorDetailActivity.class);
        intent.putExtra(VERIFY_ID, bean.getVerify_id());
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_anchordetail);
        verify_id = getIntent().getLongExtra(VERIFY_ID, 0);
        init();
        getData();
    }

    private void init() {
        imageLoader = ImageLoader.getInstance();
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.image_loading)          // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.image_loading)  // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.image_loading)       // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)                          // 设置下载的图片是否缓存在SD卡中
                .displayer(new FadeInBitmapDisplayer(200))// 图片加载好后渐入的动画时间
                .build();
        dialog_loading = new NetLoadingDailog(this);
        btn_back = findViewById(R.id.btn_back);
        btn_back.setOnClickListener(this);
        btn_share = findViewById(R.id.btn_share);
        btn_share.setOnClickListener(this);
        btn_appoint = (TextView) findViewById(R.id.btn_appoint);
        btn_appoint.setOnClickListener(this);
        iv_main = (ImageView) findViewById(R.id.iv_main);
        iv_video_flag = (ImageView) findViewById(R.id.iv_video_flag);
        iv_video_flag.setOnClickListener(this);
        mBanner = (Banner) findViewById(R.id.banner);
        mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        mBanner.setIndicatorGravity(BannerConfig.CENTER);
        tv_anchor_introduction = (TextView) findViewById(R.id.tv_anchor_introduction);
        tv_time = (TextView) findViewById(R.id.tv_time);
        tv_progress = (TextView) findViewById(R.id.tv_progress);
        tv_appoint_count = (TextView) findViewById(R.id.tv_appoint_count);
        tv_time_left = (TextView) findViewById(R.id.tv_time_left);

        btn_follow = findViewById(R.id.btn_follow);
        btn_follow.setOnClickListener(this);
        iv_like = (ImageView) findViewById(R.id.iv_like);
        tv_follow = (TextView) findViewById(R.id.tv_follow);
        layout_bottom_btn = findViewById(R.id.layout_bottom_btn);
    }

    @Override
    public void onClick(View view) {
        if (view == btn_back) {
            finish();
        } else if (view == btn_share) {
            if (shareDialog == null) {
                shareDialog = new ShareDialog(this,
                        anchorBean.getName() + "正在约播，快来支持一下吧！",
                        anchorBean.getDescription(),
                        anchorBean.getAvatar(),
                        "http://mt.201.0110net.com/m/plive.html?vid=" + verify_id + "&u=" + anchorBean.getUnique_id());
            }
            shareDialog.show();
        } else if (view == btn_appoint) {
            if (!UserConfig.getInstance().isLogin()) {
                Intent intent = new Intent(this, LoginActivity.class);
                startActivity(intent);
                return;
            }
            if (appointDialog == null) {
                appointDialog = new AppointDialog(this);
                appointDialog.setAppointDialogListener(new AppointDialog.AppointDialogListener() {
                    @Override
                    public void onBuy(long verify_id, int cost) {
                        request(new BoughtParams(verify_id, cost), BaseResponse.class, new Response.Listener<BaseResponse>() {
                            @Override
                            public void onResponse(BaseResponse onlyStatusResponse) {
                                if (onlyStatusResponse != null) {
                                    if (onlyStatusResponse.getStatusCode() == Constant.StatusCode_Success) {
                                        ToastUtil.show("购买成功");
                                        getData();
                                    } else if (onlyStatusResponse.getStatusCode() == 3) {
                                        ToastUtil.show("购买失败，余额不足");
                                    } else {
                                        ToastUtil.show("购买失败");
                                    }
                                } else {
                                    ToastUtil.show("购买失败");
                                }
                            }
                        });
                    }

                    @Override
                    public void onCancel() {

                    }
                });
            }
            appointDialog.setData(anchorBean);
            appointDialog.show();
        } else if (view == iv_video_flag) {
            String videoUrl = anchorBean.getVideos().get(0).getVideo_url();
            if (!TextUtils.isEmpty(videoUrl)) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                String type = "video/* ";
                Uri uri = Uri.parse(videoUrl);
                intent.setDataAndType(uri, type);
                startActivity(intent);
            }
        } else if (view == btn_follow) {
            if (!UserConfig.getInstance().isLogin()) {
                Intent intent = new Intent(this, LoginActivity.class);
                startActivity(intent);
                return;
            }
            followAnchor(anchorBean);
        }
    }

    private void getData() {
        dialog_loading.loading();
        request(new AnchorParams(verify_id), AnchorInfoResponse.class, new Response.Listener<AnchorInfoResponse>() {
                    @Override
                    public void onResponse(AnchorInfoResponse anchorInfoResponse) {
                        dialog_loading.dismissDialog();
                        if (anchorInfoResponse != null) {
                            Anchor anchor = anchorInfoResponse.getAnchor_info();
                            if (anchor != null) {
                                anchorBean = anchor;
                                update();
                            }
                        }
                    }
                }

        );
    }

    private void update() {
        tv_anchor_introduction.setText(TextUtils.isEmpty(anchorBean.getDescription()) ? "无介绍" : anchorBean.getDescription());
        if (anchorBean.getVideos() != null && anchorBean.getVideos().size() > 0) {
            mBanner.setVisibility(View.GONE);
            iv_main.setVisibility(View.VISIBLE);
            iv_video_flag.setVisibility(View.VISIBLE);
            imageLoader.displayImage(anchorBean.getVideos().get(0).getVideo_url(), iv_main, options);
        } else if (anchorBean.getCovers() != null && anchorBean.getCovers().size() > 0) {
            mBanner.setVisibility(View.VISIBLE);
            iv_main.setVisibility(View.GONE);
            iv_video_flag.setVisibility(View.GONE);
            final ArrayList<String> imageList = new ArrayList<>();
            for (Anchor.Cover cover : anchorBean.getCovers()) {
                imageList.add(cover.getCover_url());
            }
            mBanner.setImages(imageList);
        } else {
            mBanner.setVisibility(View.GONE);
            iv_main.setVisibility(View.VISIBLE);
            iv_video_flag.setVisibility(View.GONE);
            imageLoader.displayImage(anchorBean.getAvatar(), iv_main, options);
        }
        long startTime = 0, endTime = 0;
        if (anchorBean.getScreenings() != null && anchorBean.getScreenings().size() > 0) {
            startTime = anchorBean.getScreenings().get(0).getStart_at();
            endTime = anchorBean.getScreenings().get(0).getEnd_at();
            SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
            String startTimeText = format.format(startTime * 1000);
            String endTimeText = format.format(endTime * 1000);
            tv_time.setText(startTimeText + " 到 \n" + endTimeText);
        } else {
            tv_time.setText("待定");
        }
        tv_progress.setText(anchorBean.getPercent_shares() + "%");
        tv_appoint_count.setText(anchorBean.getBought_persons() + "人");
        tv_time_left.setText(anchorBean.getOver_plus_days() + "天");
        setFollowState(!TextUtils.isEmpty(anchorBean.getAf_id()));

        if (anchorBean.getAnchor_id() == UserConfig.getInstance().getUserId()) {
            layout_bottom_btn.setVisibility(View.GONE);
        }
    }

    private void setFollowState(boolean isFollow) {
        if (isFollow) {
            iv_like.setImageResource(R.drawable.ic_like_s);
            tv_follow.setText("取消关注");
        } else {
            iv_like.setImageResource(R.drawable.ic_like_n);
            tv_follow.setText("关注主播");
        }
    }

    private boolean isGetingData = false;

    private void followAnchor(final Anchor bean) {
        if (isGetingData || bean == null) {
            return;
        } else {
            isGetingData = true;
            final long anthorId = bean.getAnchor_id();
            if (!TextUtils.isEmpty(bean.getAf_id())) {//取消关注
                int a[] = {0, 0};
                request(new IsfocusParams(anthorId, a), BaseResponse.class, new Response.Listener<BaseResponse>() {
                    @Override
                    public void onResponse(BaseResponse onlyStatusResponse) {
                        bean.setAf_id(null);
                        ToastUtil.show("已取消关注");
                        EventBus.getDefault().post(new FocusEvent(false, anthorId));
                        setFollowState(false);
                        isGetingData = false;
                    }
                });
            } else {//关注
                int a[] = {1, 0};
                request(new IsfocusParams(anthorId, a), BaseResponse.class, new Response.Listener<BaseResponse>() {
                    @Override
                    public void onResponse(BaseResponse onlyStatusResponse) {
                        bean.setAf_id("1");
                        ToastUtil.show("关注成功");
                        EventBus.getDefault().post(new FocusEvent(true, anthorId));
                        setFollowState(true);
                        isGetingData = false;
                    }
                });
            }
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void onError() {
        super.onError();
        isGetingData = false;
        dialog_loading.dismissDialog();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (requestCode == REUQEST_LOGIN && resultCode == RESULT_OK) {
            getData();
        }
    }
}
